package com.yanghx.transaction.service;

import com.yanghx.transaction.dao.CustomerRepostory;
import com.yanghx.transaction.entity.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 注解事务
 *
 * @author yangHX
 * createTime  2019/8/9 0:27
 */
@Service
@Slf4j
public class CustomerServiceInAnnotation {

    @Resource
    private CustomerRepostory customerRepostory;

    @Resource
    private JmsTemplate jmsTemplate;

    @Transactional
    public Customer create(Customer customer) {
        log.info("CustomerService in Annotation create customer : {}", customer.getUsername());
        if (customer.getId() != null) {
            throw new RuntimeException("用户已经存在");
        }
        customer.setUsername("Annotation:" + customer.getUsername());
        jmsTemplate.convertAndSend("customer:msg:reply", customer.getUsername() + "created");
        return customerRepostory.save(customer);
    }

    @Transactional
    @JmsListener(destination = "customer:msg:new")
    public Customer createByListener(String name) {
        log.info("CustomerService In Annotation By Listener create customer : {}", name);
        Customer customer = new Customer();
        customer.setUsername("Annotation:" + customer.getUsername());
        customer.setRole("USER");
        customer.setPassword("111111");
        jmsTemplate.convertAndSend("customer:msg:reply", customer.getUsername() + "created.");
        return customerRepostory.save(customer);
    }


}
